#include <iostream>
#include <fcntl.h>
#include <unistd.h>
#include <cerrno>
#include <cstdio>

// 将文件描述符设置为非阻塞状态
void SetNodeBlock(int fd)
{
    int n = fcntl(fd, F_GETFL);

    if (n < 0)
    {
        perror("fd error");
        exit(1);
    }

    fcntl(fd, F_SETFL, n | O_NONBLOCK);
}

int main()
{

    std::string tips = "Please enter# ";

    char buffer[1024];
    SetNodeBlock(0);

    // 首先进行阻塞的测试

    while (true)
    {
        write(0, tips.c_str(), tips.size());
       
        int n = read(0, buffer, sizeof(buffer));

        if (n > 0)
        {
            std::cout << "echo# " << buffer << std::endl;
        }
        else if (n == 0)
        {
            std::cout << "read the file end" << std::endl;
            break;
        }
        else
        {
            // 对于返回值为-1,有两种情况：1、读取失败，2、底层数据未准备好
            // 通过错误码判定相应的状态

            if (errno == EAGAIN || errno == EWOULDBLOCK)
            {
                std::cout << "底层数据未就绪" << std::endl;
            }
            else if (errno == EINTR)
            {
                std::cout << "被中断，从新来" << std::endl;
            }
            else
            {
                std::cout << "read error: " << n << ", errno: " << errno << std::endl;
            }
        }

        sleep(2);
    }

    return 0;
}